package de.hsbremen.dirtybox;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Stack;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;

public class ImagesActivity extends Activity {

	private static final int IMAGE_SIZE = 90;
	private final DirtySQLiteDatabase database = new DirtySQLiteDatabase(this);
	private final Stack<TableRow> rows = new Stack<TableRow>();
	private final ArrayList<ImageView> elementViews = new ArrayList<ImageView>();
	String oldPath = "";

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.images);
		
		((Button) findViewById(R.id.addButton)).setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				showDialog(0);
			}
		});

		// Initialize/clear GUI related objects.
		this.rows.clear();
		this.elementViews.clear();
		((TableLayout) ImagesActivity.this.findViewById(R.id.table_layout))
				.removeAllViews();

		this.loadFromDatabase("folder");
		this.loadFromDatabase("image");
	}

	private void loadFromDatabase(final String what) {
		final Cursor cursor = this.database.getReadableDatabase().query(what,
				null, "ParentFolderID = ?", new String[] { "1" }, null, null,
				null, null);

		if (cursor.moveToFirst()) {
			Bitmap bm;
			byte[] byteArray;
			final int maxElementsPerRow = 4;
			if (what.equals("folder")) {
				do {
					bm = BitmapFactory.decodeResource(getResources(),
							R.drawable.folder);
					// Add each symbol to the screen.
					this.addSymbolToScreen(bm,
							cursor.getInt(cursor.getColumnIndex("_ID")), true);
				} while (cursor.moveToNext());
			} else {
				do {
					byteArray = cursor.getBlob(cursor
							.getColumnIndex("ImageData"));
					bm = BitmapFactory.decodeByteArray(byteArray, 0,
							byteArray.length);
					// Add each symbol to the screen.
					this.addSymbolToScreen(bm,
							cursor.getInt(cursor.getColumnIndex("_ID")), false);
				} while (cursor.moveToNext());
			}
		}			
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		final Dialog dialog = new Dialog(this);

		dialog.setContentView(R.layout.dialog_add_symbol);
		dialog.setTitle("Choose source of symbol");

		final Button buttonCamera = (Button) dialog
				.findViewById(R.id.symbol_from_camera);
		buttonCamera.setOnClickListener(new OnClickListener() {
			public void onClick(final View arg0) {
				final Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

				ImagesActivity.this.startActivityForResult(cameraIntent, 0);
				dismissDialog(0);
			}
		});

		final Button buttonGallery = (Button) dialog
				.findViewById(R.id.symbol_from_gallery);
		buttonGallery.setOnClickListener(new OnClickListener() {
			public void onClick(final View arg0) {

				final Intent galleryIntent = new Intent(
						Intent.ACTION_GET_CONTENT);
				galleryIntent.setType("image/*");
				ImagesActivity.this.startActivityForResult(galleryIntent, 1);
				dismissDialog(0);
			}
		});

		return dialog;
	}

	@Override
	public void onActivityResult(final int requestCode, final int resultCode,
			final Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		Log.d("DEBUG", "In: OnActivityResult");
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 0:
				// Extract the Bitmap of the just taken camera shot
				final Bitmap bitmapCamera = (Bitmap) intent.getExtras().get(
						"data");

				this.addSymbol(bitmapCamera, false);
				break;
			case 1:
				// Extract the Bitmap of the selected symbol
				final Uri selectedImageUri = intent.getData();
				final Cursor cursor = getContentResolver().query(
						selectedImageUri, null, null, null, null);

				String filePath = "";
				if (cursor.moveToFirst()) {
					// Get the path to the image.
					filePath = cursor.getString(cursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
				}
				cursor.close();

				final Bitmap bitmapGallery = BitmapFactory.decodeFile(filePath);
				this.addSymbol(bitmapGallery, false);
				break;
			}
		}
	}

	private void addSymbol(Bitmap bm, final boolean isFolder) {
		bm = Bitmap.createScaledBitmap(bm, IMAGE_SIZE, IMAGE_SIZE, false);
		// Preparing for storage as the database can
		// only store byte arrays, no bitmaps.
		final ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		final byte[] byteArray = stream.toByteArray();

		final ContentValues dataToInsert = new ContentValues();
		dataToInsert.put("ImageData", byteArray);
		dataToInsert.put("ParentFolderID", 1);
		final int elementID = (int) this.database.getWritableDatabase().insert(
				"image", null, dataToInsert);
		this.database.close();

		this.addSymbolToScreen(bm, elementID, isFolder);
	}

	// public String getPath(final Uri uri) {
	// final String[] projection = { MediaStore.Images.Media.DATA };
	// final Cursor cursor = managedQuery(uri, projection, null, null, null);
	// startManagingCursor(cursor);
	// final int column_index = cursor
	// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	// cursor.moveToFirst();
	// return cursor.getString(column_index);
	// }

	private void addSymbolToScreen(final Bitmap bm, final int elementID,
			final boolean isFolder) {
		final ImageView newElementView = new ImageView(ImagesActivity.this);

		this.setElementOnClickListener(newElementView, elementID, bm, isFolder);

		// Bring it to the screen.
		this.displaySymbol(newElementView, bm);
	}

	public void setElementOnClickListener(final ImageView elementView, final int elementID,
			final Bitmap bm, final boolean isFolder) {
		if (isFolder) {
			// TODO Alles löschen und neue Folder und Images zeigen.
		} else {
			// TODO Bild vergrößern im AlertDialog.
		}
	}

	private void displaySymbol(final ImageView elementView, final Bitmap bm) {

		elementView.setLayoutParams(new LayoutParams(110, 110));
		elementView.setClickable(true);
		elementView.setImageBitmap(bm);
		this.elementViews.add(elementView);

		final TableRow actualRow;

		// If necessary create a new TableRow
		if (((this.elementViews.size() - 1) % 4) == 0) {
			actualRow = new TableRow(ImagesActivity.this);
			this.rows.push(actualRow);

			((TableLayout) findViewById(R.id.table_layout)).addView(actualRow);
		} else {
			actualRow = this.rows.peek();
		}

		// Add the View to the actual row.
		LayoutParams params = new LayoutParams();
		params.setMargins(5, 5, 5, 5);
		elementView.setLayoutParams(params);
		actualRow.addView(elementView);
	}
}
